public class Main {
    /**
     * 移除链表元素
     * https://leetcode.cn/problems/remove-linked-list-elements/
     * 给你一个链表的头节点 head 和一个整数 val ，请你删除链表中所有满足 Node.val == val 的节点，并返回 新的头节点 。
     */
    public static void main(String[] args) {
        int[] nums = new int[]{1,2,6,3,4,5,6};
        int val = 6;
        MyList list  = new MyList();
        ListNode head = list.createMyList(nums);
        ListNode answer = new Main().removeElements(head, val);
        // 打印
        ListNode p = answer;
        System.out.print("[");
        while (p != null) {
            System.out.print(p.val);
            p = p.next;
            if (p != null) {
                System.out.print(",");
            }
        }
        System.out.println("]");
    }

    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return head;
        }

        //定义一个虚拟头结点
        ListNode virtualHead = new ListNode(val + 1, head);

        ListNode p = virtualHead;

        while (p.next != null) {
            if (p.next.val == val)
                p.next = p.next.next;
            else
                //当前节点下一个值不是val才指针右移,因为下一个值依旧可能是val
                p = p.next;
        }

        return virtualHead.next;
    }
}

class MyList {
    ListNode head;
    MyList() {
        this.head = new ListNode();
    }
    public ListNode createMyList(int[] nums) {
        if(nums.length == 0) {
            return null;
        }
        ListNode head = new ListNode();
        head.val = nums[0];
        ListNode p = head;
        for(int i = 1; i < nums.length; i++){
            p.next = new ListNode(nums[i]);
            p = p.next;
        }
        return head;
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) {
        this.val = val;
    }
    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
